 <template>
  <div class="home">
    <div class="back-button-container">
      <button class="back-button" @click="goBack">{{ t('back') }}</button>
    </div>
    <div class="auth-container">
      <h1 class="auth-title">{{ t('realNameAuth') }}</h1>
      <p class="auth-desc">
        {{ t('authBenefits') }}<br>
        {{ t('authVoluntary') }}
      </p>
      <form class="auth-form">
        <div class="form-group">
          <label for="name" class="form-label">*{{ t('realName') }}</label>
          <input
            type="text"
            id="name"
            v-model="realName"
            :placeholder="t('enterName')"
            class="form-input"
            @blur="validateName"
            @input="handleNameInput"
          >
        </div>
        <div class="form-group">
          <label for="idCard" class="form-label">*{{ t('idCardNumber') }}</label>
          <div class="idcard-wrapper">
            <input
              :type="inputType"
              id="idCard"
              v-model="displayIdCard"
              :placeholder="idCardPlaceholder"
              class="form-input"
              @keyup.enter="validateIdCardOnEnter"
              @blur="validateIdCardOnEnter"
              @input="handleIdCardInput"
            >
            <span class="toggle-icon" @click="toggleIdCardVisibility">
              {{ isIdCardVisible? '🔒' : '🔓' }}
            </span>
          </div>
        </div>
        <button
          type="button"
          @click="handleAuth"
          class="auth-button"
          :disabled="!realName ||!idCardNumber ||!agreementChecked || hasError"
        >
          {{ t('agreeAndVerify') }}
        </button>
      </form>
      <p class="auth-note">
        {{ t('faceInfoCollection') }}
      </p>
      <div class="agreement-container">
        <input
          type="checkbox"
          v-model="agreementChecked"
          class="agreement-checkbox"
          id="agreement"
        >
        <label for="agreement" class="agreement-label">
          {{ t('readAndAgree') }}《{{ t('authAgreement') }}》
        </label>
      </div>
    </div>

    <!-- 顶部轻提示 -->
    <div 
      v-if="showToast" 
      class="toast-container"
      :class="{ 'toast-visible': showToast }"
    >
      <div 
        class="toast"
        :class="['animate__animated', toastAnimation]"
      >
        {{ toastMessage }}
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { useI18n } from '@/utils/i18n'; // 导入国际化工具

// 国际化功能
const { t } = useI18n();

// 状态管理
const realName = ref('');
const idCardNumber = ref(''); // 实际存储的身份证号码
const agreementChecked = ref(false);
const showToast = ref(false);
const toastMessage = ref('');
const isIdCardVisible = ref(true); // 初始为明文显示
const router = useRouter();
const inputType = ref('text'); // 输入框类型
const toastAnimation = ref('animate__fadeInDown');
let toastTimer: any;

// 计算属性：显示的身份证号码（明文或加密）
const displayIdCard = computed(() => {
  if (isIdCardVisible.value) {
    return idCardNumber.value; // 明文显示
  } else {
    // 加密显示：前6位和后4位显示，中间用*号
    if (idCardNumber.value.length < 10) return '';
    return idCardNumber.value.slice(0, 6) + '*'.repeat(idCardNumber.value.length - 10) + idCardNumber.value.slice(-4);
  }
});

// 身份证号码输入框的占位符
const idCardPlaceholder = computed(() => {
  return isIdCardVisible.value? t('enterIdCard') : t('clickToShowIdCard');
});

// 处理姓名输入（实时存储到本地）
const handleNameInput = () => {
  saveToLocalStorage();
};

// 处理身份证号码输入（实时存储到本地）
const handleIdCardInput = (e: InputEvent) => {
  const inputValue = (e.target as HTMLInputElement).value;
  idCardNumber.value = inputValue; // 同步更新实际存储值
  saveToLocalStorage();
};

// 验证身份证号码（统一处理 blur 和 enter 事件）
const validateIdCardOnEnter = () => {
  const idCard = idCardNumber.value.trim();

  if (!idCard) {
    showToastMessage(t('pleaseEnterIdCard'));
    return false;
  }

  // 不同国家/地区的身份证格式验证可在此扩展
  if (idCard.length!== 15 && idCard.length!== 18) {
    showToastMessage(t('idCardLengthError'));
    return false;
  }

  const idCardReg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/;
  if (!idCardReg.test(idCard)) {
    showToastMessage(t('invalidIdCard'));
    return false;
  }

  if (idCard.length === 18) {
    const factors = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
    const checkCodes = ['1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'];
    let sum = 0;

    for (let i = 0; i < 17; i++) {
      sum += parseInt(idCard.charAt(i)) * factors[i];
    }

    const mod = sum % 11;
    const checkCode = checkCodes[mod];

    if (idCard.charAt(17).toUpperCase()!== checkCode) {
      showToastMessage(t('invalidIdCard'));
      return false;
    }
  }

  return true;
};

// 验证姓名
const validateName = () => {
  const name = realName.value.trim();

  if (!name) {
    showToastMessage(t('pleaseEnterName'));
    return false;
  }

  // 支持多语言姓名验证（中文、英文、日文等）
  const hasValidChars = /^[\u4e00-\u9fa5a-zA-Z\u3040-\u309F\u30A0-\u30FF\s]+$/.test(name);
  const isAllDigits = /^\d+$/.test(name);

  if (!hasValidChars || isAllDigits) {
    showToastMessage(t('invalidName'));
    return false;
  }

  if (name.length < 2) {
    showToastMessage(t('nameTooShort'));
    return false;
  }

  const hasSpecialChars = /[`~!@#$%^&*()_+<>?:"{},.\/;'[\]]/.test(name);
  if (hasSpecialChars) {
    showToastMessage(t('nameHasSpecialChars'));
    return false;
  }

  return true;
};

// 显示轻提示
const showToastMessage = (message: string) => {
  toastMessage.value = message;
  showToast.value = true;
  toastAnimation.value = 'animate__fadeInDown';
  
  if (toastTimer) {
    clearTimeout(toastTimer);
  }
  
  toastTimer = setTimeout(() => {
    hideToast();
  }, 3000);
};

// 隐藏轻提示
const hideToast = () => {
  toastAnimation.value = 'animate__fadeOutUp';
  setTimeout(() => {
    showToast.value = false;
  }, 300);
};

// 检查是否有错误
const hasError = computed(() => {
  return!realName.value.trim() ||!idCardNumber.value.trim() || showToast.value; 
});

// 切换身份证号码显示/加密状态
const toggleIdCardVisibility = () => {
  isIdCardVisible.value =!isIdCardVisible.value;
  inputType.value = isIdCardVisible.value? 'text' : 'password';
};

// 保存到本地存储
const saveToLocalStorage = () => {
  try {
    localStorage.setItem('realName', realName.value.trim() || '');
    localStorage.setItem('idCardNumber', idCardNumber.value.trim() || '');
    
    if (realName.value.trim() && idCardNumber.value.trim()) {
      localStorage.setItem('isIdentityVerified', 'true');
    }
  } catch (error) {
    console.error('本地存储失败:', error);
    showToastMessage(t('saveFailed'));
  }
};

// 处理认证
const handleAuth = () => {
  const isNameValid = validateName();
  const isIdCardValid = validateIdCardOnEnter();

  if (!isNameValid ||!isIdCardValid) {
    return;
  }

  if (realName.value && idCardNumber.value && agreementChecked.value) {
    saveToLocalStorage();
    showToastMessage(t('authSuccess'));
    
    setTimeout(() => {
      router.push('/sfz')
       .catch((error) => {
          console.error('路由跳转失败:', error);
          showToastMessage(t('jumpFailed'));
        });
    }, 1500);
  } else {
    if (!agreementChecked.value) {
      showToastMessage(t('pleaseAgreeProtocol')); 
    } else {
      showToastMessage(t('pleaseCompleteInfo'));
    }
  }
};

// 返回函数
const goBack = () => {
  router.push('/my');
};

// 组件挂载时从本地存储加载数据
onMounted(() => {
  try {
    const savedName = localStorage.getItem('realName');
    const savedIdCard = localStorage.getItem('idCardNumber');
    
    if (savedName) {
      realName.value = savedName;
    }
    if (savedIdCard) {
      idCardNumber.value = savedIdCard;
    }
  } catch (error) {
    console.error('加载本地存储失败:', error);
    showToastMessage(t('loadFailed'));
  }
});
</script>

<style scoped>
.back-button-container {
  position: absolute;
  top: 10px;
  left: 10px;
  z-index: 1001;
}
.back-button {
  padding: 5px 10px;
  background-color: #54EA8C;
  color: white;
  border: none;
  border-radius: 5px;
  cursor: pointer;
}
.auth-container {
  background-color: white;
  padding: 20px;
  height: 90vh;
  border-radius: 10px;
}

.auth-title {
  text-align: center;
  color: #333;
  margin-bottom: 20px;
}

.auth-desc {
  text-align: justify;
  color: #666;
  margin-bottom: 20px;
}

.auth-form {
  display: flex;
  flex-direction: column;
}

.form-group {
  margin-bottom: 20px;
}

.form-label {
  display: block;
  color: #333;
  margin-bottom: 5px;
}

.form-input {
  width: 100%;
  padding: 10px;
  border: 1px solid #ccc;
  border-radius: 5px;
}

.auth-button {
  padding: 10px 20px;
  background-color: #54EA8C;
  color: white;
  border: none;
  border-radius: 5px;
  font-size: 16px;
  cursor: pointer;
}

.auth-button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.auth-note {
  text-align: justify;
  color: #666;
  margin-bottom: 10px;
}

.agreement-container {
  display: flex;
  align-items: center;
  margin-top: 10px;
}

.agreement-checkbox {
  margin-right: 10px;
}

.agreement-label {
  color: #666;
  cursor: pointer;
}

.idcard-wrapper {
  position: relative;
}

.toggle-icon {
  position: absolute;
  right: 10px;
  top: 50%;
  transform: translateY(-50%);
  cursor: pointer;
  color: #333;
}

.toast-container {
  position: fixed;
  top: -50px;
  left: 50%;
  transform: translateX(-50%);
  width: 80%;
  max-width: 400px;
  z-index: 1000;
  transition: top 0.3s ease;
}

.toast-visible {
  top: 20px;
}

.toast {
  background-color: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 10px 15px;
  border-radius: 4px;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  text-align: center;
}

@import 'https://cdn.jsdelivr.net/npm/animate.css@4.1.1/animate.min.css';
</style>